import styles from './index.less';
import React, { useEffect, useState } from 'react';
import { Button, Form, Input, InputNumber, Modal, Popconfirm, Switch, message } from 'antd';
import type { TableColumnsType } from 'antd';
import type { CategoryType, formDataType } from './components/SearchForm';
import type { Query_Type_GetGoodsListParams } from '@/services/ant-design-pro/good';
import { PlusOutlined } from '@ant-design/icons';

import {
  getGoodsList,
  getSingleGoodInfo,
  getCategoryList,
  delGoodList,
  changeGoodStatus,
  changeGoodPartInfo,
} from '@/services/ant-design-pro/good';

import { PageContainer } from '@ant-design/pro-components';

import Tables from './components/Tables';
import SearchForm from './components/SearchForm';

import Modals from './components/Modals';
import FormItem from 'antd/es/form/FormItem';

export type DataType = {
  key: React.Key;
  id: string;
  name: string;
  price: number;
  status: number;
  virtualSale: number;
  ordered: number;
  coverUrl: string;
};

export type isEditType = {
  id: number;
  ordered: number;
  virtualSale: number;
};

const Goods: React.FC = () => {
  const [isAddGoodModalOpen, setIsAddGoodModalOpen] = useState(false);
  const [isChangeGoodModalOpen, setIsChangeGoodModalOpen] = useState(false);
  const [initialValues, setInitialValues] = useState();
  const [goodList, setGoodList] = useState<DataType[]>([]);
  const [total, setTotal] = useState(0);
  const [reqData, setReqData] = useState<Query_Type_GetGoodsListParams>({
    name: '',
    channelId: undefined,
    page: 1,
    pageSize: 5,
  });
  const [idEditTable, setIsEditTable] = useState(false);
  const [isEdit, setIsEdit] = useState<isEditType>({ id: 0, ordered: 0, virtualSale: 0 });
  const [editForm] = Form.useForm();

  const reset = () => {
    setReqData({
      name: '',
      channelId: undefined,
      page: 1,
      pageSize: 5,
    });
  };

  const init = async () => {
    const res = await getGoodsList(reqData);

    if (res.code === 0) {
      setGoodList(res.data.records);
      setTotal(res.data.total);
    } else {
      message.info(res.msg);
      setGoodList([]);
      setTotal(0);
    }
  };

  const openChangeGoodModal = async (goodsId: string) => {
    try {
      const res = await getSingleGoodInfo(goodsId);
      if (res && res.code === 0) {
        setInitialValues(res.data);
        setIsChangeGoodModalOpen(true);
      } else {
        console.error('操作失败:', res.msg);
      }
    } catch (error) {
      console.error('请求失败:', error);
    }
  };

  const delSingleGood = async (id: string) => {
    try {
      const res = await delGoodList(id);
      if (res.code === 0) {
        message.success('删除成功');
        reset();
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      console.log('商品删除过程中出现错误');
    }
  };

  const handleChangeGoodStatus = async (id: number, checked: boolean) => {
    console.log(id, checked);
    try {
      const res = await changeGoodStatus({
        id,
        status: checked ? 0 : 1,
      });
      if (res.code === 0) {
        message.success(`成功${checked ? '上' : '下'}架商品`);
        init();
      }
    } catch (error) {}
  };

  const handleEditTable = (data: isEditType) => {
    setIsEdit(data);
    setIsEditTable(true);

    editForm.setFieldsValue({
      ordered: data.ordered,
      virtualSale: data.virtualSale,
    });
  };

  const handleSubmitChange = async (values: any) => {
    // console.log(values);
    const res = await changeGoodPartInfo({
      id: isEdit.id,
      ordered: values.ordered,
      virtualSale: values.virtualSale,
    });
    if (res && res.code === 0) {
      message.success('修改成功');
      setIsEditTable(false);
      init();
    } else {
      message.error(res.msg);
    }
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '封面图片',
      dataIndex: 'coverUrl',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <img className={styles.img} src={record.coverUrl} alt="" />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <>
          {/* <img className={styles.img} src={record.coverUrl} alt="" /> */}
          <span>{record.name}</span>
        </>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      align: 'center',
    },
    {
      title: '上架',
      dataIndex: 'status',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <>
          <Switch
            defaultChecked={record.status ? false : true}
            onChange={(checked) => handleChangeGoodStatus(Number(record.id), checked)}
          />
        </>
      ),
    },
    {
      title: '虚拟销量',
      dataIndex: 'virtualSale',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <Input disabled style={{ width: '50px' }} value={record.virtualSale} />
      ),
    },
    {
      title: '排序',
      dataIndex: 'ordered',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <Input disabled style={{ width: '50px' }} value={record.ordered} />
      ),
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'x',
      width: '150px',
      fixed: 'right',
      align: 'center',
      render: (_: unknown, record: DataType) => (
        <div>
          <a
            style={{ marginRight: '20px' }}
            onClick={() =>
              handleEditTable({
                id: record.id,
                ordered: record.ordered,
                virtualSale: record.virtualSale,
              })
            }
          >
            编辑
          </a>
          <a style={{ marginRight: '20px' }} onClick={() => openChangeGoodModal(record.id)}>
            修改
          </a>
          <Popconfirm
            title="确定要删除这个商品吗？"
            onConfirm={() => delSingleGood(record.id)}
            // onCancel={cancel}
            okText="Yes"
            cancelText="No"
            placement="left"
          >
            <a className={styles.delBtn}>删除</a>
          </Popconfirm>
        </div>
      ),
    },
  ];

  /** 获取商品列表 */
  const handleSearchFormChange = (values: formDataType) => {
    //搜索时重置当前页为第一页
    setReqData({
      page: 1,
      pageSize: 5,
      ...values,
    });

    console.log(values);
  };

  const handlePageChange = (currentPage: number, pageSize: number) => {
    console.log('当前页数', currentPage, '页大小', pageSize);
    setReqData({
      ...reqData,
      page: currentPage,
      pageSize: pageSize,
    });
  };

  useEffect(() => {
    init();
  }, [reqData]);

  /** 获取分类数据 */
  const [categoryList, setCategoryList] = useState<CategoryType[]>();

  const fetchGetCategoryList = async () => {
    try {
      const res = await getCategoryList();
      if (res && res.code === 0) {
        const list = res.data?.map((item: any) => ({
          value: +item.id,
          label: item.channelName,
        }));
        // list.unshift({ value: '', label: '全部' });
        setCategoryList(list);
      } else {
        message.error(res.msg);
      }
    } catch (error) {}
  };

  useEffect(() => {
    fetchGetCategoryList();
  }, []);

  return (
    <>
      <PageContainer>
        <div className={styles.header}>
          <SearchForm
            onSearchFormChange={handleSearchFormChange}
            categoryList={categoryList as CategoryType[]}
          />
          <Button
            className={styles.addBtn}
            icon={<PlusOutlined />}
            onClick={() => setIsAddGoodModalOpen(true)}
          >
            添加商品
          </Button>
        </div>
        <Tables
          data={goodList}
          columns={columns}
          pagination={{
            total,
            current: reqData.page as number,
            pageSize: reqData.pageSize as number,
            pageSizeOptions: [5, 10, 20, 50],
            onChange: handlePageChange,
          }}
          // onPageChange={handlePageChange}
          onReset={reset}
          onInit={init}
        />
        <Modals
          title="添加商品"
          isModalOpen={isAddGoodModalOpen}
          setIsModalOpen={setIsAddGoodModalOpen}
          categoryList={categoryList as CategoryType[]}
          init={init}
        />
        <Modals
          type={1}
          title="修改商品"
          isModalOpen={isChangeGoodModalOpen}
          setIsModalOpen={setIsChangeGoodModalOpen}
          categoryList={categoryList as CategoryType[]}
          initialValues={initialValues}
          init={init}
        />
        <Modal
          title="Basic Modal"
          open={idEditTable}
          footer={null}
          onOk={() => setIsEditTable(false)}
          onCancel={() => setIsEditTable(false)}
        >
          <Form form={editForm} onFinish={handleSubmitChange}>
            <FormItem name="virtualSale" label="虚拟销量">
              <InputNumber min={0} max={1000} width={'100%'} />
            </FormItem>
            <FormItem name="ordered" label="排序">
              <InputNumber min={0} max={1000} width={'100%'} />
            </FormItem>
            <FormItem>
              <Button type="primary" htmlType="submit">
                确认修改
              </Button>
            </FormItem>
          </Form>
        </Modal>
      </PageContainer>
    </>
  );
};
export default Goods;
